package com.zifan.sever.utils;

import cn.hutool.core.util.IdUtil;
import com.zifan.sever.config.minio.MinioProperties;
import com.zifan.sever.config.minio.MinioTemplate;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件操作的工具类
 * @author Zifan
 * @date 2021年05月29日9:09
 */
@Component
public class FileUtil {
    @Autowired
    private MinioProperties minioProperties;

    /**
     * 获取minioProperties配置对象
     * @return
     */
    public MinioProperties getMinioProperties(){
        return minioProperties;
    }

    /**
     * 获取一个minioTemplate
     */
    public MinioTemplate getMinioTemplate(){
        return new MinioTemplate(getMinioClient());
    }

    /**
     *获取一个MinioClient
     */
    public MinioClient getMinioClient (){
        MinioClient minioClient = null;
        try {
            minioClient = new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
        } catch (InvalidEndpointException e) {
            e.printStackTrace();
        } catch (InvalidPortException e) {
            e.printStackTrace();
        }
        return minioClient;
    }

    /**
     * 修改文件名字，防止重复上传
     */
    public String changeFileName(String fileName){
        Date date = new Date();
        String format = new SimpleDateFormat("yyyy-MM").format(date);
        String simpleUUID = IdUtil.simpleUUID();
        return "/" + format + "/" + simpleUUID + fileName;
    }
}
